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, Value, VarId,
4    VirtualPathId,
5    ast::Block,
6    debugger::{Debugger, NoopDebugger},
7    engine::{
8        CachedFile, Command, DEFAULT_OVERLAY_NAME, EnvName, EnvVars, OverlayFrame, ScopeFrame,
9        Stack, StateDelta, Variable, Visibility,
10        description::{Doccomments, build_desc},
11    },
12    eval_const::create_nu_constant,
13    report_error::ReportLog,
14    shell_error::{generic::GenericError, io::IoError},
15};
16use fancy_regex::Regex;
17use lru::LruCache;
18use nu_path::AbsolutePathBuf;
19use std::{
20    collections::HashMap,
21    num::NonZeroUsize,
22    path::PathBuf,
23    sync::{
24        Arc, Mutex, MutexGuard, PoisonError,
25        atomic::{AtomicBool, AtomicU32, Ordering},
26        mpsc::Sender,
27        mpsc::channel,
28    },
29};
30
31type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
32
33#[cfg(feature = "plugin")]
34use crate::{PluginRegistryFile, PluginRegistryItem, RegisteredPlugin};
35
36use super::{CurrentJob, Jobs, Mail, Mailbox, ThreadJob};
37
38#[derive(Clone, Debug)]
39pub enum VirtualPath {
40    File(FileId),
41    Dir(Vec<VirtualPathId>),
42}
43
44pub struct ReplState {
45    pub buffer: String,
46    // A byte position, as `EditCommand::MoveToPosition` is also a byte position
47    pub cursor_pos: usize,
48    /// Immediately accept the buffer on the next loop.
49    pub accept: bool,
50}
51
52pub struct IsDebugging(AtomicBool);
53
54impl IsDebugging {
55    pub fn new(val: bool) -> Self {
56        IsDebugging(AtomicBool::new(val))
57    }
58}
59
60impl Clone for IsDebugging {
61    fn clone(&self) -> Self {
62        IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
63    }
64}
65
66/// The core global engine state. This includes all global definitions as well as any global state that
67/// will persist for the whole session.
68///
69/// Declarations, variables, blocks, and other forms of data are held in the global state and referenced
70/// elsewhere using their IDs. These IDs are simply their index into the global state. This allows us to
71/// more easily handle creating blocks, binding variables and callsites, and more, because each of these
72/// will refer to the corresponding IDs rather than their definitions directly. At runtime, this means
73/// less copying and smaller structures.
74///
75/// Many of the larger objects in this structure are stored within `Arc` to decrease the cost of
76/// cloning `EngineState`. While `Arc`s are generally immutable, they can be modified using
77/// `Arc::make_mut`, which automatically clones to a new allocation if there are other copies of
78/// the `Arc` already in use, but will let us modify the `Arc` directly if we have the only
79/// reference to it.
80///
81/// Note that the runtime stack is not part of this global state. Runtime stacks are handled differently,
82/// but they also rely on using IDs rather than full definitions.
83#[derive(Clone)]
84pub struct EngineState {
85    files: Vec<CachedFile>,
86    pub(super) virtual_paths: Vec<(String, VirtualPath)>,
87    vars: Vec<Variable>,
88    decls: Arc<Vec<Box<dyn Command + 'static>>>,
89    // The Vec is wrapped in Arc so that if we don't need to modify the list, we can just clone
90    // the reference and not have to clone each individual Arc inside. These lists can be
91    // especially long, so it helps
92    pub(super) blocks: Arc<Vec<Arc<Block>>>,
93    pub(super) modules: Arc<Vec<Arc<Module>>>,
94    pub spans: Vec<Span>,
95    doccomments: Doccomments,
96    pub scope: ScopeFrame,
97    signals: Signals,
98    pub signal_handlers: Option<Handlers>,
99    pub env_vars: Arc<EnvVars>,
100    pub previous_env_vars: Arc<HashMap<String, Value>>,
101    pub config: Arc<Config>,
102    pub pipeline_externals_state: Arc<(AtomicU32, AtomicU32)>,
103    pub repl_state: Arc<Mutex<ReplState>>,
104    pub table_decl_id: Option<DeclId>,
105    #[cfg(feature = "plugin")]
106    pub plugin_path: Option<PathBuf>,
107    #[cfg(feature = "plugin")]
108    plugins: Vec<Arc<dyn RegisteredPlugin>>,
109    config_path: HashMap<String, PathBuf>,
110    pub history_enabled: bool,
111    pub history_session_id: i64,
112    // Path to the file Nushell is currently evaluating, or None if we're in an interactive session.
113    pub file: Option<PathBuf>,
114    pub regex_cache: Arc<Mutex<LruCache<String, Regex>>>,
115    pub is_interactive: bool,
116    pub is_login: bool,
117    pub is_lsp: bool,
118    pub is_mcp: bool,
119    startup_time: i64,
120    is_debugging: IsDebugging,
121    pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
122    pub report_log: Arc<Mutex<ReportLog>>,
123
124    pub jobs: Arc<Mutex<Jobs>>,
125
126    // The job being executed with this engine state, or None if main thread
127    pub current_job: CurrentJob,
128
129    pub root_job_sender: Sender<Mail>,
130
131    // When there are background jobs running, the interactive behavior of `exit` changes depending on
132    // the value of this flag:
133    // - if this is false, then a warning about running jobs is shown and `exit` enables this flag
134    // - if this is true, then `exit` will `std::process::exit`
135    //
136    // This ensures that running exit twice will terminate the program correctly
137    pub exit_warning_given: Arc<AtomicBool>,
138}
139
140// The max number of compiled regexes to keep around in a LRU cache, arbitrarily chosen
141const REGEX_CACHE_SIZE: usize = 100; // must be nonzero, otherwise will panic
142
143pub const NU_VARIABLE_ID: VarId = VarId::new(0);
144pub const IN_VARIABLE_ID: VarId = VarId::new(1);
145pub const ENV_VARIABLE_ID: VarId = VarId::new(2);
146// NOTE: If you add more to this list, make sure to update the > checks based on the last in the list
147
148// The first span is unknown span
149pub const UNKNOWN_SPAN_ID: SpanId = SpanId::new(0);
150
151impl EngineState {
152    pub fn new() -> Self {
153        let (send, recv) = channel::<Mail>();
154
155        Self {
156            files: vec![],
157            virtual_paths: vec![],
158            vars: vec![
159                Variable::new(Span::new(0, 0), Type::Any, false),
160                Variable::new(Span::new(0, 0), Type::Any, false),
161                Variable::new(Span::new(0, 0), Type::Any, false),
162                Variable::new(Span::new(0, 0), Type::Any, false),
163                Variable::new(Span::new(0, 0), Type::Any, false),
164            ],
165            decls: Arc::new(vec![]),
166            blocks: Arc::new(vec![]),
167            modules: Arc::new(vec![Arc::new(Module::new(
168                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
169            ))]),
170            spans: vec![Span::unknown()],
171            doccomments: Doccomments::new(),
172            // make sure we have some default overlay:
173            scope: ScopeFrame::with_empty_overlay(
174                DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
175                ModuleId::new(0),
176                false,
177            ),
178            signal_handlers: None,
179            signals: Signals::empty(),
180            env_vars: Arc::new(
181                [(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
182                    .into_iter()
183                    .collect(),
184            ),
185            previous_env_vars: Arc::new(HashMap::new()),
186            config: Arc::new(Config::default()),
187            pipeline_externals_state: Arc::new((AtomicU32::new(0), AtomicU32::new(0))),
188            repl_state: Arc::new(Mutex::new(ReplState {
189                buffer: "".to_string(),
190                cursor_pos: 0,
191                accept: false,
192            })),
193            table_decl_id: None,
194            #[cfg(feature = "plugin")]
195            plugin_path: None,
196            #[cfg(feature = "plugin")]
197            plugins: vec![],
198            config_path: HashMap::new(),
199            history_enabled: true,
200            history_session_id: 0,
201            file: None,
202            regex_cache: Arc::new(Mutex::new(LruCache::new(
203                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
204            ))),
205            is_interactive: false,
206            is_login: false,
207            is_lsp: false,
208            is_mcp: false,
209            startup_time: -1,
210            is_debugging: IsDebugging::new(false),
211            debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
212            report_log: Arc::default(),
213            jobs: Arc::new(Mutex::new(Jobs::default())),
214            current_job: CurrentJob {
215                id: JobId::new(0),
216                background_thread_job: None,
217                mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
218            },
219            root_job_sender: send,
220            exit_warning_given: Arc::new(AtomicBool::new(false)),
221        }
222    }
223
224    pub fn signals(&self) -> &Signals {
225        &self.signals
226    }
227
228    pub fn reset_signals(&mut self) {
229        self.signals.reset();
230        if let Some(ref handlers) = self.signal_handlers {
231            handlers.run(SignalAction::Reset);
232        }
233    }
234
235    pub fn set_signals(&mut self, signals: Signals) {
236        self.signals = signals;
237    }
238
239    /// Merges a `StateDelta` onto the current state. These deltas come from a system, like the parser, that
240    /// creates a new set of definitions and visible symbols in the current scope. We make this transactional
241    /// as there are times when we want to run the parser and immediately throw away the results (namely:
242    /// syntax highlighting and completions).
243    ///
244    /// When we want to preserve what the parser has created, we can take its output (the `StateDelta`) and
245    /// use this function to merge it into the global state.
246    pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
247        // Take the mutable reference and extend the permanent state from the working set
248        self.files.extend(delta.files);
249        self.virtual_paths.extend(delta.virtual_paths);
250        self.vars.extend(delta.vars);
251        self.spans.extend(delta.spans);
252        self.doccomments.merge_with(delta.doccomments);
253
254        // Avoid potentially cloning the Arcs if we aren't adding anything
255        if !delta.decls.is_empty() {
256            Arc::make_mut(&mut self.decls).extend(delta.decls);
257        }
258        if !delta.blocks.is_empty() {
259            Arc::make_mut(&mut self.blocks).extend(delta.blocks);
260        }
261        if !delta.modules.is_empty() {
262            Arc::make_mut(&mut self.modules).extend(delta.modules);
263        }
264
265        let first = delta.scope.remove(0);
266
267        for (delta_name, delta_overlay) in first.clone().overlays {
268            if let Some((_, existing_overlay)) = self
269                .scope
270                .overlays
271                .iter_mut()
272                .find(|(name, _)| name == &delta_name)
273            {
274                // Updating existing overlay
275                for item in delta_overlay.decls.into_iter() {
276                    existing_overlay.decls.insert(item.0, item.1);
277                }
278                for item in delta_overlay.vars.into_iter() {
279                    existing_overlay.insert_variable(item.0, item.1);
280                }
281                for item in delta_overlay.modules.into_iter() {
282                    existing_overlay.modules.insert(item.0, item.1);
283                }
284
285                existing_overlay
286                    .visibility
287                    .merge_with(delta_overlay.visibility);
288            } else {
289                // New overlay was added to the delta
290                self.scope.overlays.push((delta_name, delta_overlay));
291            }
292        }
293
294        let mut activated_ids = self.translate_overlay_ids(&first);
295
296        let mut removed_ids = vec![];
297
298        for name in &first.removed_overlays {
299            if let Some(overlay_id) = self.find_overlay(name) {
300                removed_ids.push(overlay_id);
301            }
302        }
303
304        // Remove overlays removed in delta
305        self.scope
306            .active_overlays
307            .retain(|id| !removed_ids.contains(id));
308
309        // Move overlays activated in the delta to be first
310        self.scope
311            .active_overlays
312            .retain(|id| !activated_ids.contains(id));
313        self.scope.active_overlays.append(&mut activated_ids);
314
315        #[cfg(feature = "plugin")]
316        if !delta.plugins.is_empty() {
317            for plugin in std::mem::take(&mut delta.plugins) {
318                // Connect plugins to the signal handlers
319                if let Some(handlers) = &self.signal_handlers {
320                    plugin.clone().configure_signal_handler(handlers)?;
321                }
322
323                // Replace plugins that overlap in identity.
324                if let Some(existing) = self
325                    .plugins
326                    .iter_mut()
327                    .find(|p| p.identity().name() == plugin.identity().name())
328                {
329                    // Stop the existing plugin, so that the new plugin definitely takes over
330                    existing.stop()?;
331                    *existing = plugin;
332                } else {
333                    self.plugins.push(plugin);
334                }
335            }
336        }
337
338        #[cfg(feature = "plugin")]
339        if !delta.plugin_registry_items.is_empty() {
340            // Update the plugin file with the new signatures.
341            if self.plugin_path.is_some() {
342                self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
343            }
344        }
345
346        Ok(())
347    }
348
349    /// Merge the environment from the runtime Stack into the engine state
350    pub fn merge_env(&mut self, stack: &mut Stack) -> Result<(), ShellError> {
351        for mut scope in stack.env_vars.drain(..) {
352            for (overlay_name, mut env) in Arc::make_mut(&mut scope).drain() {
353                if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
354                    // Updating existing overlay
355                    env_vars.extend(env.drain());
356                } else {
357                    // Pushing a new overlay
358                    Arc::make_mut(&mut self.env_vars).insert(overlay_name, env);
359                }
360            }
361        }
362
363        let cwd = self.cwd(Some(stack))?;
364        std::env::set_current_dir(cwd)
365            .map_err(|err| IoError::new_internal(err, "Could not set current dir"))?;
366
367        if let Some(config) = stack.config.take() {
368            // If config was updated in the stack, replace it.
369            self.config = config;
370
371            // Make plugin GC config changes take effect immediately.
372            #[cfg(feature = "plugin")]
373            self.update_plugin_gc_configs(&self.config.plugin_gc);
374        }
375
376        Ok(())
377    }
378
379    /// Clean up unused variables from a Stack to prevent memory leaks.
380    /// This removes variables that are no longer referenced by any overlay.
381    pub fn cleanup_stack_variables(&mut self, stack: &mut Stack) {
382        use std::collections::HashSet;
383
384        let mut shadowed_vars = HashSet::new();
385        for (_, frame) in self.scope.overlays.iter_mut() {
386            shadowed_vars.extend(frame.shadowed_vars.to_owned());
387            frame.shadowed_vars.clear();
388        }
389
390        // Remove variables from stack that are no longer referenced
391        stack
392            .vars
393            .retain(|(var_id, _)| !shadowed_vars.contains(var_id));
394    }
395
396    pub fn active_overlay_ids<'a, 'b>(
397        &'b self,
398        removed_overlays: &'a [Vec<u8>],
399    ) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
400    where
401        'b: 'a,
402    {
403        self.scope.active_overlays.iter().filter(|id| {
404            !removed_overlays
405                .iter()
406                .any(|name| name == self.get_overlay_name(**id))
407        })
408    }
409
410    pub fn active_overlays<'a, 'b>(
411        &'b self,
412        removed_overlays: &'a [Vec<u8>],
413    ) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
414    where
415        'b: 'a,
416    {
417        self.active_overlay_ids(removed_overlays)
418            .map(|id| self.get_overlay(*id))
419    }
420
421    pub fn active_overlay_names<'a, 'b>(
422        &'b self,
423        removed_overlays: &'a [Vec<u8>],
424    ) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
425    where
426        'b: 'a,
427    {
428        self.active_overlay_ids(removed_overlays)
429            .map(|id| self.get_overlay_name(*id))
430    }
431
432    /// Translate overlay IDs from other to IDs in self
433    fn translate_overlay_ids(&self, other: &ScopeFrame) -> Vec<OverlayId> {
434        let other_names = other.active_overlays.iter().map(|other_id| {
435            &other
436                .overlays
437                .get(other_id.get())
438                .expect("internal error: missing overlay")
439                .0
440        });
441
442        other_names
443            .map(|other_name| {
444                self.find_overlay(other_name)
445                    .expect("internal error: missing overlay")
446            })
447            .collect()
448    }
449
450    pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
451        self.active_overlay_names(removed_overlays)
452            .last()
453            .expect("internal error: no active overlays")
454    }
455
456    pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
457        self.active_overlay_ids(removed_overlays)
458            .last()
459            .map(|id| self.get_overlay(*id))
460            .expect("internal error: no active overlays")
461    }
462
463    pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
464        &self
465            .scope
466            .overlays
467            .get(overlay_id.get())
468            .expect("internal error: missing overlay")
469            .0
470    }
471
472    pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
473        &self
474            .scope
475            .overlays
476            .get(overlay_id.get())
477            .expect("internal error: missing overlay")
478            .1
479    }
480
481    pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
482        let mut result: HashMap<&str, &Value> = HashMap::new();
483
484        for overlay_name in self.active_overlay_names(&[]) {
485            let name = String::from_utf8_lossy(overlay_name);
486            if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
487                result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
488            }
489        }
490
491        result
492    }
493
494    pub fn add_env_var(&mut self, name: String, val: Value) {
495        let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
496
497        if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
498            env_vars.insert(EnvName::from(name), val);
499        } else {
500            Arc::make_mut(&mut self.env_vars).insert(
501                overlay_name,
502                [(EnvName::from(name), val)].into_iter().collect(),
503            );
504        }
505    }
506
507    pub fn get_env_var(&self, name: &str) -> Option<&Value> {
508        for overlay_id in self.scope.active_overlays.iter().rev() {
509            let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
510            if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref())
511                && let Some(val) = env_vars.get(&EnvName::from(name))
512            {
513                return Some(val);
514            }
515        }
516
517        None
518    }
519
520    #[cfg(feature = "plugin")]
521    pub fn plugins(&self) -> &[Arc<dyn RegisteredPlugin>] {
522        &self.plugins
523    }
524
525    #[cfg(feature = "plugin")]
526    fn update_plugin_file(&self, updated_items: Vec<PluginRegistryItem>) -> Result<(), ShellError> {
527        // Updating the signatures plugin file with the added signatures
528        use std::fs::File;
529
530        let plugin_path = self.plugin_path.as_ref().ok_or_else(|| {
531            ShellError::Generic(
532                GenericError::new_internal("Plugin file path not set", "")
533                    .with_help("you may be running nu with --no-config-file"),
534            )
535        })?;
536
537        // Read the current contents of the plugin file if it exists
538        let mut contents = match File::open(plugin_path.as_path()) {
539            Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
540            Err(err) => {
541                if err.kind() == std::io::ErrorKind::NotFound {
542                    Ok(PluginRegistryFile::default())
543                } else {
544                    Err(ShellError::Io(IoError::new_internal_with_path(
545                        err,
546                        "Failed to open plugin file",
547                        PathBuf::from(plugin_path),
548                    )))
549                }
550            }
551        }?;
552
553        // Update the given signatures
554        for item in updated_items {
555            contents.upsert_plugin(item);
556        }
557
558        // Write it to the same path
559        let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
560            IoError::new_internal_with_path(
561                err,
562                "Failed to write plugin file",
563                PathBuf::from(plugin_path),
564            )
565        })?;
566
567        contents.write_to(plugin_file, None)
568    }
569
570    /// Update plugins with new garbage collection config
571    #[cfg(feature = "plugin")]
572    fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
573        for plugin in &self.plugins {
574            plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
575        }
576    }
577
578    pub fn num_files(&self) -> usize {
579        self.files.len()
580    }
581
582    pub fn num_virtual_paths(&self) -> usize {
583        self.virtual_paths.len()
584    }
585
586    pub fn num_vars(&self) -> usize {
587        self.vars.len()
588    }
589
590    pub fn num_decls(&self) -> usize {
591        self.decls.len()
592    }
593
594    pub fn num_blocks(&self) -> usize {
595        self.blocks.len()
596    }
597
598    pub fn num_modules(&self) -> usize {
599        self.modules.len()
600    }
601
602    pub fn num_spans(&self) -> usize {
603        self.spans.len()
604    }
605    pub fn print_vars(&self) {
606        for var in self.vars.iter().enumerate() {
607            println!("var{}: {:?}", var.0, var.1);
608        }
609    }
610
611    pub fn print_decls(&self) {
612        for decl in self.decls.iter().enumerate() {
613            println!("decl{}: {:?}", decl.0, decl.1.signature());
614        }
615    }
616
617    pub fn print_blocks(&self) {
618        for block in self.blocks.iter().enumerate() {
619            println!("block{}: {:?}", block.0, block.1);
620        }
621    }
622
623    pub fn print_contents(&self) {
624        for cached_file in self.files.iter() {
625            let string = String::from_utf8_lossy(&cached_file.content);
626            println!("{string}");
627        }
628    }
629
630    /// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
631    ///
632    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
633    pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
634        let mut visibility: Visibility = Visibility::new();
635
636        for overlay_frame in self.active_overlays(removed_overlays).rev() {
637            visibility.append(&overlay_frame.visibility);
638
639            if let Some(decl_id) = overlay_frame.get_decl(name)
640                && visibility.is_decl_id_visible(&decl_id)
641            {
642                return Some(decl_id);
643            }
644        }
645
646        None
647    }
648
649    /// Find the name of the declaration corresponding to `decl_id`.
650    ///
651    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
652    pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
653        let mut visibility: Visibility = Visibility::new();
654
655        for overlay_frame in self.active_overlays(removed_overlays).rev() {
656            visibility.append(&overlay_frame.visibility);
657
658            if visibility.is_decl_id_visible(&decl_id) {
659                for (name, id) in overlay_frame.decls.iter() {
660                    if id == &decl_id {
661                        return Some(name);
662                    }
663                }
664            }
665        }
666
667        None
668    }
669
670    /// Find the [`OverlayId`](crate::OverlayId) corresponding to `name`.
671    ///
672    /// Searches all overlays, not just active overlays. To search only in active overlays, use [`find_active_overlay`](EngineState::find_active_overlay)
673    pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
674        self.scope.find_overlay(name)
675    }
676
677    /// Find the [`OverlayId`](crate::OverlayId) of the active overlay corresponding to `name`.
678    ///
679    /// Searches only active overlays. To search in all overlays, use [`find_overlay`](EngineState::find_active_overlay)
680    pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
681        self.scope.find_active_overlay(name)
682    }
683
684    /// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
685    ///
686    /// Searches within active overlays, and filtering out overlays in `removed_overlays`.
687    pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
688        for overlay_frame in self.active_overlays(removed_overlays).rev() {
689            if let Some(module_id) = overlay_frame.modules.get(name) {
690                return Some(*module_id);
691            }
692        }
693
694        None
695    }
696
697    pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
698        self.doccomments.get_module_comments(module_id)
699    }
700
701    #[cfg(feature = "plugin")]
702    pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
703        let mut unique_plugin_decls = HashMap::new();
704
705        // Make sure there are no duplicate decls: Newer one overwrites the older one
706        for decl in self.decls.iter().filter(|d| d.is_plugin()) {
707            unique_plugin_decls.insert(decl.name(), decl);
708        }
709
710        let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
711            unique_plugin_decls.into_iter().collect();
712
713        // Sort the plugins by name so we don't end up with a random plugin file each time
714        plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
715        plugin_decls.into_iter().map(|(_, decl)| decl)
716    }
717
718    pub fn which_module_has_decl(
719        &self,
720        decl_name: &[u8],
721        removed_overlays: &[Vec<u8>],
722    ) -> Option<&[u8]> {
723        for overlay_frame in self.active_overlays(removed_overlays).rev() {
724            for (module_name, module_id) in overlay_frame.modules.iter() {
725                let module = self.get_module(*module_id);
726                if module.has_decl(decl_name) {
727                    return Some(module_name);
728                }
729            }
730        }
731
732        None
733    }
734
735    /// Apply a function to all commands. The function accepts a command name and its DeclId
736    pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
737        for overlay_frame in self.active_overlays(&[]).rev() {
738            for (name, decl_id) in &overlay_frame.decls {
739                if overlay_frame.visibility.is_decl_id_visible(decl_id) {
740                    f(name, *decl_id);
741                }
742            }
743        }
744    }
745
746    pub fn get_span_contents(&self, span: Span) -> &[u8] {
747        self.try_get_file_contents(span).unwrap_or(&[0u8; 0])
748    }
749
750    pub fn try_get_file_contents(&self, span: Span) -> Option<&[u8]> {
751        self.files.iter().find_map(|file| {
752            if file.covered_span.contains_span(span) {
753                let start = span.start - file.covered_span.start;
754                let end = span.end - file.covered_span.start;
755                Some(&file.content[start..end])
756            } else {
757                None
758            }
759        })
760    }
761
762    /// If the span's content starts with the given prefix, return two subspans
763    /// corresponding to this prefix, and the rest of the content.
764    pub fn span_match_prefix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
765        let contents = self.get_span_contents(span);
766
767        if contents.starts_with(prefix) {
768            span.split_at(prefix.len())
769        } else {
770            None
771        }
772    }
773
774    /// If the span's content ends with the given postfix, return two subspans
775    /// corresponding to the rest of the content, and this postfix.
776    pub fn span_match_postfix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
777        let contents = self.get_span_contents(span);
778
779        if contents.ends_with(prefix) {
780            span.split_at(span.len() - prefix.len())
781        } else {
782            None
783        }
784    }
785
786    /// Get the global config from the engine state.
787    ///
788    /// Use [`Stack::get_config()`] instead whenever the `Stack` is available, as it takes into
789    /// account local changes to `$env.config`.
790    pub fn get_config(&self) -> &Arc<Config> {
791        &self.config
792    }
793
794    pub fn set_config(&mut self, conf: impl Into<Arc<Config>>) {
795        let conf = conf.into();
796
797        #[cfg(feature = "plugin")]
798        if conf.plugin_gc != self.config.plugin_gc {
799            // Make plugin GC config changes take effect immediately.
800            self.update_plugin_gc_configs(&conf.plugin_gc);
801        }
802
803        self.config = conf;
804    }
805
806    /// Fetch the configuration for a plugin
807    ///
808    /// The `plugin` must match the registered name of a plugin.  For `plugin add
809    /// nu_plugin_example` the plugin name to use will be `"example"`
810    pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
811        self.config.plugins.get(plugin)
812    }
813
814    /// Returns the configuration settings for command history or `None` if history is disabled
815    pub fn history_config(&self) -> Option<HistoryConfig> {
816        self.history_enabled.then(|| self.config.history.clone())
817    }
818
819    pub fn get_var(&self, var_id: VarId) -> &Variable {
820        self.vars
821            .get(var_id.get())
822            .expect("internal error: missing variable")
823    }
824
825    pub fn get_constant(&self, var_id: VarId) -> Option<&Value> {
826        let var = self.get_var(var_id);
827        var.const_val.as_ref()
828    }
829
830    pub fn generate_nu_constant(&mut self) {
831        self.vars[NU_VARIABLE_ID.get()].const_val = Some(create_nu_constant(self, Span::unknown()));
832    }
833
834    pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
835        self.decls
836            .get(decl_id.get())
837            .expect("internal error: missing declaration")
838            .as_ref()
839    }
840
841    /// Get all commands within scope, sorted by the commands' names
842    pub fn get_decls_sorted(&self, include_hidden: bool) -> Vec<(Vec<u8>, DeclId)> {
843        let mut decls_map = HashMap::new();
844
845        for overlay_frame in self.active_overlays(&[]) {
846            let new_decls = if include_hidden {
847                overlay_frame.decls.clone()
848            } else {
849                overlay_frame
850                    .decls
851                    .clone()
852                    .into_iter()
853                    .filter(|(_, id)| overlay_frame.visibility.is_decl_id_visible(id))
854                    .collect()
855            };
856
857            decls_map.extend(new_decls);
858        }
859
860        let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
861
862        decls.sort_by(|a, b| a.0.cmp(&b.0));
863        decls
864    }
865
866    pub fn get_signature(&self, decl: &dyn Command) -> Signature {
867        if let Some(block_id) = decl.block_id() {
868            *self.blocks[block_id.get()].signature.clone()
869        } else {
870            decl.signature()
871        }
872    }
873
874    /// Get signatures of all commands within scope with their decl ids.
875    pub fn get_signatures_and_declids(&self, include_hidden: bool) -> Vec<(Signature, DeclId)> {
876        self.get_decls_sorted(include_hidden)
877            .into_iter()
878            .map(|(_, id)| {
879                let decl = self.get_decl(id);
880
881                (self.get_signature(decl).update_from_command(decl), id)
882            })
883            .collect()
884    }
885
886    pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
887        self.blocks
888            .get(block_id.get())
889            .expect("internal error: missing block")
890    }
891
892    /// Optionally get a block by id, if it exists
893    ///
894    /// Prefer to use [`.get_block()`](Self::get_block) in most cases - `BlockId`s that don't exist
895    /// are normally a compiler error. This only exists to stop plugins from crashing the engine if
896    /// they send us something invalid.
897    pub fn try_get_block(&self, block_id: BlockId) -> Option<&Arc<Block>> {
898        self.blocks.get(block_id.get())
899    }
900
901    pub fn get_module(&self, module_id: ModuleId) -> &Module {
902        self.modules
903            .get(module_id.get())
904            .expect("internal error: missing module")
905    }
906
907    pub fn get_virtual_path(&self, virtual_path_id: VirtualPathId) -> &(String, VirtualPath) {
908        self.virtual_paths
909            .get(virtual_path_id.get())
910            .expect("internal error: missing virtual path")
911    }
912
913    pub fn next_span_start(&self) -> usize {
914        if let Some(cached_file) = self.files.last() {
915            cached_file.covered_span.end
916        } else {
917            0
918        }
919    }
920
921    pub fn files(
922        &self,
923    ) -> impl DoubleEndedIterator<Item = &CachedFile> + ExactSizeIterator<Item = &CachedFile> {
924        self.files.iter()
925    }
926
927    pub fn add_file(&mut self, filename: Arc<str>, content: Arc<[u8]>) -> FileId {
928        let next_span_start = self.next_span_start();
929        let next_span_end = next_span_start + content.len();
930
931        let covered_span = Span::new(next_span_start, next_span_end);
932
933        self.files.push(CachedFile {
934            name: filename,
935            content,
936            covered_span,
937        });
938
939        FileId::new(self.num_files() - 1)
940    }
941
942    pub fn set_config_path(&mut self, key: &str, val: PathBuf) {
943        self.config_path.insert(key.to_string(), val);
944    }
945
946    pub fn get_config_path(&self, key: &str) -> Option<&PathBuf> {
947        self.config_path.get(key)
948    }
949
950    pub fn build_desc(&self, spans: &[Span]) -> (String, String) {
951        let comment_lines: Vec<&[u8]> = spans
952            .iter()
953            .map(|span| self.get_span_contents(*span))
954            .collect();
955        build_desc(&comment_lines)
956    }
957
958    pub fn build_module_desc(&self, module_id: ModuleId) -> Option<(String, String)> {
959        self.get_module_comments(module_id)
960            .map(|comment_spans| self.build_desc(comment_spans))
961    }
962
963    /// Returns the current working directory, which is guaranteed to be canonicalized.
964    ///
965    /// Returns an empty String if $env.PWD doesn't exist.
966    #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")]
967    pub fn current_work_dir(&self) -> String {
968        self.cwd(None)
969            .map(|path| path.to_string_lossy().to_string())
970            .unwrap_or_default()
971    }
972
973    /// Returns the current working directory, which is guaranteed to be an
974    /// absolute path without trailing slashes (unless it's the root path), but
975    /// might contain symlink components.
976    ///
977    /// If `stack` is supplied, also considers modifications to the working
978    /// directory on the stack that have yet to be merged into the engine state.
979    pub fn cwd(&self, stack: Option<&Stack>) -> Result<AbsolutePathBuf, ShellError> {
980        // Helper function to create a simple generic error.
981        fn error(msg: &str, cwd: impl AsRef<nu_path::Path>) -> ShellError {
982            ShellError::Generic(
983                GenericError::new_internal(
984                    msg.to_string(),
985                    format!("$env.PWD = {}", cwd.as_ref().display()),
986                )
987                .with_help("Use `cd` to reset $env.PWD into a good state"),
988            )
989        }
990
991        // Retrieve $env.PWD from the stack or the engine state.
992        let pwd = if let Some(stack) = stack {
993            stack.get_env_var(self, "PWD")
994        } else {
995            self.get_env_var("PWD")
996        };
997
998        let pwd = pwd.ok_or_else(|| error("$env.PWD not found", ""))?;
999
1000        if let Ok(pwd) = pwd.as_str() {
1001            let path = AbsolutePathBuf::try_from(pwd)
1002                .map_err(|_| error("$env.PWD is not an absolute path", pwd))?;
1003
1004            // Technically, a root path counts as "having trailing slashes", but
1005            // for the purpose of PWD, a root path is acceptable.
1006            if path.parent().is_some() && nu_path::has_trailing_slash(path.as_ref()) {
1007                Err(error("$env.PWD contains trailing slashes", &path))
1008            } else if !path.exists() {
1009                Err(error("$env.PWD points to a non-existent directory", &path))
1010            } else if !path.is_dir() {
1011                Err(error("$env.PWD points to a non-directory", &path))
1012            } else {
1013                Ok(path)
1014            }
1015        } else {
1016            Err(error("$env.PWD is not a string", format!("{pwd:?}")))
1017        }
1018    }
1019
1020    /// Like `EngineState::cwd()`, but returns a String instead of a PathBuf for convenience.
1021    pub fn cwd_as_string(&self, stack: Option<&Stack>) -> Result<String, ShellError> {
1022        let cwd = self.cwd(stack)?;
1023        cwd.into_os_string()
1024            .into_string()
1025            .map_err(|err| ShellError::NonUtf8Custom {
1026                msg: format!("The current working directory is not a valid utf-8 string: {err:?}"),
1027                span: Span::unknown(),
1028            })
1029    }
1030
1031    // TODO: see if we can completely get rid of this
1032    pub fn get_file_contents(&self) -> &[CachedFile] {
1033        &self.files
1034    }
1035
1036    pub fn get_startup_time(&self) -> i64 {
1037        self.startup_time
1038    }
1039
1040    pub fn set_startup_time(&mut self, startup_time: i64) {
1041        self.startup_time = startup_time;
1042    }
1043
1044    pub fn activate_debugger(
1045        &self,
1046        debugger: Box<dyn Debugger>,
1047    ) -> Result<(), PoisonDebuggerError<'_>> {
1048        let mut locked_debugger = self.debugger.lock()?;
1049        *locked_debugger = debugger;
1050        locked_debugger.activate();
1051        self.is_debugging.0.store(true, Ordering::Relaxed);
1052        Ok(())
1053    }
1054
1055    pub fn deactivate_debugger(&self) -> Result<Box<dyn Debugger>, PoisonDebuggerError<'_>> {
1056        let mut locked_debugger = self.debugger.lock()?;
1057        locked_debugger.deactivate();
1058        let ret = std::mem::replace(&mut *locked_debugger, Box::new(NoopDebugger));
1059        self.is_debugging.0.store(false, Ordering::Relaxed);
1060        Ok(ret)
1061    }
1062
1063    pub fn is_debugging(&self) -> bool {
1064        self.is_debugging.0.load(Ordering::Relaxed)
1065    }
1066
1067    pub fn recover_from_panic(&mut self) {
1068        if Mutex::is_poisoned(&self.repl_state) {
1069            self.repl_state = Arc::new(Mutex::new(ReplState {
1070                buffer: "".to_string(),
1071                cursor_pos: 0,
1072                accept: false,
1073            }));
1074        }
1075        if Mutex::is_poisoned(&self.jobs) {
1076            self.jobs = Arc::new(Mutex::new(Jobs::default()));
1077        }
1078        if Mutex::is_poisoned(&self.regex_cache) {
1079            self.regex_cache = Arc::new(Mutex::new(LruCache::new(
1080                NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
1081            )));
1082        }
1083    }
1084
1085    /// Add new span and return its ID
1086    pub fn add_span(&mut self, span: Span) -> SpanId {
1087        self.spans.push(span);
1088        SpanId::new(self.num_spans() - 1)
1089    }
1090
1091    /// Find ID of a span (should be avoided if possible)
1092    pub fn find_span_id(&self, span: Span) -> Option<SpanId> {
1093        self.spans
1094            .iter()
1095            .position(|sp| sp == &span)
1096            .map(SpanId::new)
1097    }
1098
1099    // Determines whether the current state is being held by a background job
1100    pub fn is_background_job(&self) -> bool {
1101        self.current_job.background_thread_job.is_some()
1102    }
1103
1104    // Gets the thread job entry
1105    pub fn current_thread_job(&self) -> Option<&ThreadJob> {
1106        self.current_job.background_thread_job.as_ref()
1107    }
1108}
1109
1110impl GetSpan for &EngineState {
1111    /// Get existing span
1112    fn get_span(&self, span_id: SpanId) -> Span {
1113        *self
1114            .spans
1115            .get(span_id.get())
1116            .expect("internal error: missing span")
1117    }
1118}
1119
1120impl Default for EngineState {
1121    fn default() -> Self {
1122        Self::new()
1123    }
1124}
1125
1126#[cfg(test)]
1127mod engine_state_tests {
1128    use crate::engine::StateWorkingSet;
1129    use std::str::{Utf8Error, from_utf8};
1130
1131    use super::*;
1132
1133    #[test]
1134    fn add_file_gives_id() {
1135        let engine_state = EngineState::new();
1136        let mut engine_state = StateWorkingSet::new(&engine_state);
1137        let id = engine_state.add_file("test.nu".into(), &[]);
1138
1139        assert_eq!(id, FileId::new(0));
1140    }
1141
1142    #[test]
1143    fn add_file_gives_id_including_parent() {
1144        let mut engine_state = EngineState::new();
1145        let parent_id = engine_state.add_file("test.nu".into(), Arc::new([]));
1146
1147        let mut working_set = StateWorkingSet::new(&engine_state);
1148        let working_set_id = working_set.add_file("child.nu".into(), &[]);
1149
1150        assert_eq!(parent_id, FileId::new(0));
1151        assert_eq!(working_set_id, FileId::new(1));
1152    }
1153
1154    #[test]
1155    fn merge_states() -> Result<(), ShellError> {
1156        let mut engine_state = EngineState::new();
1157        engine_state.add_file("test.nu".into(), Arc::new([]));
1158
1159        let delta = {
1160            let mut working_set = StateWorkingSet::new(&engine_state);
1161            let _ = working_set.add_file("child.nu".into(), &[]);
1162            working_set.render()
1163        };
1164
1165        engine_state.merge_delta(delta)?;
1166
1167        assert_eq!(engine_state.num_files(), 2);
1168        assert_eq!(&*engine_state.files[0].name, "test.nu");
1169        assert_eq!(&*engine_state.files[1].name, "child.nu");
1170
1171        Ok(())
1172    }
1173
1174    #[test]
1175    fn list_variables() -> Result<(), Utf8Error> {
1176        let varname = "something";
1177        let varname_with_sigil = "$".to_owned() + varname;
1178        let engine_state = EngineState::new();
1179        let mut working_set = StateWorkingSet::new(&engine_state);
1180        working_set.add_variable(
1181            varname.as_bytes().into(),
1182            Span { start: 0, end: 1 },
1183            Type::Int,
1184            false,
1185        );
1186        let variables = working_set
1187            .list_variables()
1188            .into_iter()
1189            .map(from_utf8)
1190            .collect::<Result<Vec<&str>, Utf8Error>>()?;
1191        assert_eq!(variables, vec![varname_with_sigil]);
1192        Ok(())
1193    }
1194
1195    #[test]
1196    fn get_plugin_config() {
1197        let mut engine_state = EngineState::new();
1198
1199        assert!(
1200            engine_state.get_plugin_config("example").is_none(),
1201            "Unexpected plugin configuration"
1202        );
1203
1204        let mut plugins = HashMap::new();
1205        plugins.insert("example".into(), Value::string("value", Span::test_data()));
1206
1207        let mut config = Config::clone(engine_state.get_config());
1208        config.plugins = plugins;
1209
1210        engine_state.set_config(config);
1211
1212        assert!(
1213            engine_state.get_plugin_config("example").is_some(),
1214            "Plugin configuration not found"
1215        );
1216    }
1217}
1218
1219#[cfg(test)]
1220mod test_cwd {
1221    //! Here're the test cases we need to cover:
1222    //!
1223    //! `EngineState::cwd()` computes the result from `self.env_vars["PWD"]` and
1224    //! optionally `stack.env_vars["PWD"]`.
1225    //!
1226    //! PWD may be unset in either `env_vars`.
1227    //! PWD should NOT be an empty string.
1228    //! PWD should NOT be a non-string value.
1229    //! PWD should NOT be a relative path.
1230    //! PWD should NOT contain trailing slashes.
1231    //! PWD may point to a directory or a symlink to directory.
1232    //! PWD should NOT point to a file or a symlink to file.
1233    //! PWD should NOT point to non-existent entities in the filesystem.
1234
1235    use crate::{
1236        Value,
1237        engine::{EngineState, Stack},
1238    };
1239    use nu_path::{AbsolutePath, Path, assert_path_eq};
1240    use tempfile::{NamedTempFile, TempDir};
1241
1242    /// Creates a symlink. Works on both Unix and Windows.
1243    #[cfg(any(unix, windows))]
1244    fn symlink(
1245        original: impl AsRef<AbsolutePath>,
1246        link: impl AsRef<AbsolutePath>,
1247    ) -> std::io::Result<()> {
1248        let original = original.as_ref();
1249        let link = link.as_ref();
1250
1251        #[cfg(unix)]
1252        {
1253            std::os::unix::fs::symlink(original, link)
1254        }
1255        #[cfg(windows)]
1256        {
1257            if original.is_dir() {
1258                std::os::windows::fs::symlink_dir(original, link)
1259            } else {
1260                std::os::windows::fs::symlink_file(original, link)
1261            }
1262        }
1263    }
1264
1265    /// Create an engine state initialized with the given PWD.
1266    fn engine_state_with_pwd(path: impl AsRef<Path>) -> EngineState {
1267        let mut engine_state = EngineState::new();
1268        engine_state.add_env_var(
1269            "PWD".into(),
1270            Value::test_string(path.as_ref().to_str().unwrap()),
1271        );
1272        engine_state
1273    }
1274
1275    /// Create a stack initialized with the given PWD.
1276    fn stack_with_pwd(path: impl AsRef<Path>) -> Stack {
1277        let mut stack = Stack::new();
1278        stack.add_env_var(
1279            "PWD".into(),
1280            Value::test_string(path.as_ref().to_str().unwrap()),
1281        );
1282        stack
1283    }
1284
1285    #[test]
1286    fn pwd_not_set() {
1287        let engine_state = EngineState::new();
1288        engine_state.cwd(None).unwrap_err();
1289    }
1290
1291    #[test]
1292    fn pwd_is_empty_string() {
1293        let engine_state = engine_state_with_pwd("");
1294        engine_state.cwd(None).unwrap_err();
1295    }
1296
1297    #[test]
1298    fn pwd_is_non_string_value() {
1299        let mut engine_state = EngineState::new();
1300        engine_state.add_env_var("PWD".into(), Value::test_glob("*"));
1301        engine_state.cwd(None).unwrap_err();
1302    }
1303
1304    #[test]
1305    fn pwd_is_relative_path() {
1306        let engine_state = engine_state_with_pwd("./foo");
1307
1308        engine_state.cwd(None).unwrap_err();
1309    }
1310
1311    #[test]
1312    fn pwd_has_trailing_slash() {
1313        let dir = TempDir::new().unwrap();
1314        let engine_state = engine_state_with_pwd(dir.path().join(""));
1315
1316        engine_state.cwd(None).unwrap_err();
1317    }
1318
1319    #[test]
1320    fn pwd_points_to_root() {
1321        #[cfg(windows)]
1322        let root = Path::new(r"C:\");
1323        #[cfg(not(windows))]
1324        let root = Path::new("/");
1325
1326        let engine_state = engine_state_with_pwd(root);
1327        let cwd = engine_state.cwd(None).unwrap();
1328        assert_path_eq!(cwd, root);
1329    }
1330
1331    #[test]
1332    fn pwd_points_to_normal_file() {
1333        let file = NamedTempFile::new().unwrap();
1334        let engine_state = engine_state_with_pwd(file.path());
1335
1336        engine_state.cwd(None).unwrap_err();
1337    }
1338
1339    #[test]
1340    fn pwd_points_to_normal_directory() {
1341        let dir = TempDir::new().unwrap();
1342        let engine_state = engine_state_with_pwd(dir.path());
1343
1344        let cwd = engine_state.cwd(None).unwrap();
1345        assert_path_eq!(cwd, dir.path());
1346    }
1347
1348    #[test]
1349    fn pwd_points_to_symlink_to_file() {
1350        let file = NamedTempFile::new().unwrap();
1351        let temp_file = AbsolutePath::try_new(file.path()).unwrap();
1352        let dir = TempDir::new().unwrap();
1353        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1354
1355        let link = temp.join("link");
1356        symlink(temp_file, &link).unwrap();
1357        let engine_state = engine_state_with_pwd(&link);
1358
1359        engine_state.cwd(None).unwrap_err();
1360    }
1361
1362    #[test]
1363    fn pwd_points_to_symlink_to_directory() {
1364        let dir = TempDir::new().unwrap();
1365        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1366
1367        let link = temp.join("link");
1368        symlink(temp, &link).unwrap();
1369        let engine_state = engine_state_with_pwd(&link);
1370
1371        let cwd = engine_state.cwd(None).unwrap();
1372        assert_path_eq!(cwd, link);
1373    }
1374
1375    #[test]
1376    fn pwd_points_to_broken_symlink() {
1377        let dir = TempDir::new().unwrap();
1378        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1379        let other_dir = TempDir::new().unwrap();
1380        let other_temp = AbsolutePath::try_new(other_dir.path()).unwrap();
1381
1382        let link = temp.join("link");
1383        symlink(other_temp, &link).unwrap();
1384        let engine_state = engine_state_with_pwd(&link);
1385
1386        drop(other_dir);
1387        engine_state.cwd(None).unwrap_err();
1388    }
1389
1390    #[test]
1391    fn pwd_points_to_nonexistent_entity() {
1392        let engine_state = engine_state_with_pwd(TempDir::new().unwrap().path());
1393
1394        engine_state.cwd(None).unwrap_err();
1395    }
1396
1397    #[test]
1398    fn stack_pwd_not_set() {
1399        let dir = TempDir::new().unwrap();
1400        let engine_state = engine_state_with_pwd(dir.path());
1401        let stack = Stack::new();
1402
1403        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1404        assert_eq!(cwd, dir.path());
1405    }
1406
1407    #[test]
1408    fn stack_pwd_is_empty_string() {
1409        let dir = TempDir::new().unwrap();
1410        let engine_state = engine_state_with_pwd(dir.path());
1411        let stack = stack_with_pwd("");
1412
1413        engine_state.cwd(Some(&stack)).unwrap_err();
1414    }
1415
1416    #[test]
1417    fn stack_pwd_points_to_normal_directory() {
1418        let dir1 = TempDir::new().unwrap();
1419        let dir2 = TempDir::new().unwrap();
1420        let engine_state = engine_state_with_pwd(dir1.path());
1421        let stack = stack_with_pwd(dir2.path());
1422
1423        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1424        assert_path_eq!(cwd, dir2.path());
1425    }
1426
1427    #[test]
1428    fn stack_pwd_points_to_normal_directory_with_symlink_components() {
1429        let dir = TempDir::new().unwrap();
1430        let temp = AbsolutePath::try_new(dir.path()).unwrap();
1431
1432        // `/tmp/dir/link` points to `/tmp/dir`, then we set PWD to `/tmp/dir/link/foo`
1433        let link = temp.join("link");
1434        symlink(temp, &link).unwrap();
1435        let foo = link.join("foo");
1436        std::fs::create_dir(temp.join("foo")).unwrap();
1437        let engine_state = EngineState::new();
1438        let stack = stack_with_pwd(&foo);
1439
1440        let cwd = engine_state.cwd(Some(&stack)).unwrap();
1441        assert_path_eq!(cwd, foo);
1442    }
1443}